package com.lwlk.zdk.controller.Post;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lwlk.zdk.annotation.JwtIgnore;
import com.lwlk.zdk.annotation.MyLog;
import com.lwlk.zdk.enums.RetCode;
import com.lwlk.zdk.mapper.T.TDisDictionaryMapper;
import com.lwlk.zdk.mapper.T.TDisEnterpriseMapper;
import com.lwlk.zdk.mapper.T.TDisPlatformMapper;
import com.lwlk.zdk.mapper.pw.pwCheckTheDutyMessageMapper;
import com.lwlk.zdk.mapper.pw.pwMessageMapper;
import com.lwlk.zdk.mapper.pw.pwUserMapper;
import com.lwlk.zdk.mapper.pw.pwVehicleMessageMapper;
import com.lwlk.zdk.model.CommonUser;
import com.lwlk.zdk.model.Encapsulation.EncapsulationIsAnswerIssue;
import com.lwlk.zdk.model.pw.*;
import com.lwlk.zdk.service.EnterpriseService.EnterpriseService;
import com.lwlk.zdk.service.User.JoinService;
import com.lwlk.zdk.service.PostService.PostMessageService;
import com.lwlk.zdk.service.User.SysUserService;
import com.lwlk.zdk.util.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;


import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

@Api(value = "查岗信息")
@RestController
@Transactional
@RequestMapping(value = "/message")
public class PostMessageController {

    private static final Logger log = LoggerFactory.getLogger(PostMessageController.class);

    @Autowired
    PostMessageService postMessageService;
    @Autowired
    JoinService joinService;
    @Autowired
    EnterpriseService enterpriseService;
    @Autowired
    TDisPlatformMapper disPlatformMapper;
    @Autowired
    pwVehicleMessageMapper pwVehicleMessageMapper;
    @Autowired
    pwCheckTheDutyMessageMapper pwCheckTheDutyMessageMapper;
    @Autowired
    TDisDictionaryMapper disDictionaryMapper;
    @Autowired
    TDisEnterpriseMapper disEnterpriseMapper;
    @Autowired
    pwMessageMapper pwMessageMapper;
    @Autowired
    pwUserMapper pwUserMapper;

    private final static String port = PropUtils.getString("ports");
    private final static String Ip = PropUtils.getString("Ip");
    private final static String clientCode = PropUtils.getString("clientCode");

    //=======查岗问题新增====================
    @ApiOperation(value = "查岗问题新增")
    @MyLog(value = "新增查岗问题信息")  //这里添加了AOP的自定义注解
    @RequestMapping(value = "/add",method = RequestMethod.POST)
    public Response add(@RequestBody  pwCheckTheDutyIssue pwCheckTheDutyIssue,HttpServletRequest request){
        Response response = new Response();
        try {
            Boolean flag=listerUtil.getRoleType(request);
            if (flag==false){
                response.setCode(RetCode.ACCOUNT_EXIST);
                response.setMsg("此账号为监管员账号,不可进行操作");
                return response;
            }
            pwCheckTheDutyIssue.setTopicType("简答题");
            int count=postMessageService.add(pwCheckTheDutyIssue);
            response.setData(count);
            response.setCode(RetCode.SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
        }
        return response;
    }

    //=======查岗问题批量删除====================
    @ApiOperation(value = "查岗问题批量删除")
    @MyLog(value = "批量删除查岗问题信息")  //这里添加了AOP的自定义注解
    @RequestMapping(value = "/deleteBatch",method = RequestMethod.POST)
    public Response delete(Integer[] id){
        Response response=new Response();
       try {
           for (Integer integer : id) {
               int count=postMessageService.deleteBatch(integer);
               response.setData(count);
           }

               response.setCode(RetCode.SUCCESS);
               response.setMsg("操作成功");

       }catch (Exception e){
           e.printStackTrace();
       }
       return response;
    }

    //=======查岗问题修改====================
    @ApiOperation(value = "查岗问题修改")
    @MyLog(value = "修改查岗问题信息")  //这里添加了AOP的自定义注解
    @RequestMapping(value = "/update",method = RequestMethod.POST)
    public Response update(@RequestBody pwCheckTheDutyIssue pwCheckTheDutyIssue,HttpServletRequest request){
        Response response=new Response();
        try {
            Boolean flag=listerUtil.getRoleType(request);
            if (flag==false){
                response.setCode(RetCode.ACCOUNT_EXIST);
                response.setMsg("此账号为监管员账号,不可进行操作");
                return response;
            }
            int count=postMessageService.update(pwCheckTheDutyIssue);
            response.setData(count);
            response.setCode(RetCode.SUCCESS);
            response.setMsg("操作成功");
        }catch (Exception e){
            e.printStackTrace();
        }
        return response;
    }


    //=======查岗问题详情====================
    @ApiOperation(value = "查岗问题详情")
    @RequestMapping(value = "/details",method = RequestMethod.GET)
    public Response details(Integer id){
        Response response=new Response();
        try {
            pwCheckTheDutyIssue pwCheckTheDutyIssue=postMessageService.details(id);
            response.setCode(RetCode.SUCCESS);
            response.setData(pwCheckTheDutyIssue);
            response.setMsg("操作成功");
        }catch (Exception e){
            e.printStackTrace();
        }
        return response;
    }


    //=======根据创建人和问题查询====================
    @ApiOperation(value = "根据创建人和问题查询")
    @RequestMapping(value = "/query",method = RequestMethod.GET)
    public LayuiTablePagingResult query(String topic, String creator, Integer page, Integer size){
      LayuiTablePagingResult result=null;
      try {
           PageHelper.startPage(page,size);
               List<pwCheckTheDutyIssue> pwCheckTheDutyIssue=postMessageService.query(topic,creator);
               PageInfo<pwCheckTheDutyIssue> pageInfo=new PageInfo<pwCheckTheDutyIssue>(pwCheckTheDutyIssue);
               result = new LayuiTablePagingResult();
               result.setCode(RetCode.SUCCESS.getCode());
               result.setMsg(RetCode.SUCCESS.getMsg());
               result.setCount(pageInfo.getTotal());
               result.setData(pageInfo.getList());
               Long totalPages = pageInfo.getTotal() / size;
               if (pageInfo.getTotal() % size != 0){
              totalPages ++;
              }
              result.setTotalPages(totalPages);
      }catch (Exception e){
          e.printStackTrace();
      }
      return result;
    }



    //=======我的报文管理信息展示(查询本平台的查岗信息)====================
    @ApiOperation(value = "我的报文管理信息展示(查询本平台的查岗信息)----建议废除")
    @RequestMapping(value = "/showTheLaidOff",method = RequestMethod.GET)
    public LayuiTablePagingResult show(Integer page, Integer size, Integer platformId, Integer isReply, Date startTime,Date endTime){
      LayuiTablePagingResult result=null;
      try {
          PageHelper.startPage(page,size);
              List<pwMessage> pwMessageList=postMessageService.selectDim(platformId,startTime,isReply,endTime);
              PageInfo<pwMessage>pageInfo=new PageInfo<>(pwMessageList);
              result = new LayuiTablePagingResult();
              result.setCode(RetCode.SUCCESS.getCode());
              result.setMsg(RetCode.SUCCESS.getMsg());
              result.setCount(pageInfo.getTotal());
              result.setData(pageInfo.getList());
              Long totalPages = pageInfo.getTotal() / size;
              if (pageInfo.getTotal() % size != 0){
                  totalPages ++;
              }
              result.setTotalPages(totalPages);
      }catch (Exception e){
          e.printStackTrace();
      }
      return result;
    }

    @ApiOperation(value = "报文详情")
    @RequestMapping(value = "/messageDetails",method = RequestMethod.GET)
    public Response getMessageDetails(Integer messageId){
        Response response=new Response();
        List<Map>messageDetails=postMessageService.selectMessageDetails(messageId);
        response.setData(messageDetails);
        response.setCode(RetCode.SUCCESS);
        response.setMsg("执行成功");
        return response;
    }

    //======下级平台报文管理==============
    @ApiOperation(value = "下级平台报文管理")
    @RequestMapping(value = "/subordinateMessage",method = RequestMethod.GET)
    public LayuiTablePagingResult subordinate(Integer page, Integer size, String startTime,String endTime,Integer uId,String messageObjectType,Integer platformIds){
        LayuiTablePagingResult result=null;
        try {
            PageHelper.startPage(page,size);

            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            if (startTime!=null&&endTime!=null){
                if (startTime.equals(endTime)){
                    Date date =df.parse(endTime);
                    date.setTime(date.getTime() + 1000);
                    endTime=df.format(date);
                }
            }
                List<Map<String,Object>> pwMessageList=postMessageService.selectSubordinate(startTime,endTime,uId,messageObjectType,platformIds);
                PageInfo pageInfo=new PageInfo(pwMessageList);
                result = new LayuiTablePagingResult();
                result.setCode(RetCode.SUCCESS.getCode());
                result.setMsg(RetCode.SUCCESS.getMsg());
                result.setCount(pageInfo.getTotal());
                result.setData(pageInfo.getList());
            Long totalPages = pageInfo.getTotal() / size;
            if (pageInfo.getTotal() % size != 0){
                totalPages ++;
            }
            result.setTotalPages(totalPages);
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }


    @ApiOperation(value = "平台被查岗记录")
    @RequestMapping(value = "/platformRecord",method = RequestMethod.GET)
    public LayuiTablePagingResult getPlatformRecord(Integer page,Integer size,Integer uId,Integer platformId,String checkTime){
       LayuiTablePagingResult result=null;
       try {
           PageHelper.startPage(page,size);
           List<Map<String,Object>>platformRecordList=postMessageService.selectPlatformRecord(uId,platformId,checkTime);
           PageInfo pageInfo=new PageInfo<>(platformRecordList);
           result = new LayuiTablePagingResult();
           result.setCode(RetCode.SUCCESS.getCode());
           result.setMsg(RetCode.SUCCESS.getMsg());
           result.setCount(pageInfo.getTotal());
           result.setData(pageInfo.getList());
           Long totalPages = pageInfo.getTotal() / size;
           if (pageInfo.getTotal() % size != 0){
               totalPages ++;
           }
           result.setTotalPages(totalPages);
       }catch (Exception e){
           e.printStackTrace();
       }
       return result;
    }



    //=======向接入平台查岗(查某一个平台)platformId:要查询的平台,platformIds:查询平台,enterpriseId:接入业户id====================
    @ApiOperation(value = "向接入平台查岗(查某一个平台)")
    @RequestMapping(value = "/issueJunior",method = RequestMethod.POST)
    public Response issue(String roleType, Integer platformId, Integer platformIds, String objectType, Integer enterpriseId, String topicType, String regionCode, Integer uId, HttpServletRequest request){
        Response response=new Response();
        try {
            Boolean flag=listerUtil.getRoleType(request);
            if (flag==false){
                response.setCode(RetCode.ACCOUNT_EXIST);
                response.setMsg("此账号为监管员账号,不可进行操作");
                return response;
            }
            Boolean flage=listerUtil.getLevel(request);
            if (flage==false) {
                    response.setCode(RetCode.ACCOUNT_EXIST);
                    response.setMsg("该账号没有此权限");
                    return response;
            }
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//Date指定格式：yyyy-MM-dd HH:mm:ss:SSS
            Date date=new Date();
            String s=simpleDateFormat.format(date);
            Date date1=simpleDateFormat.parse(s);
            String objectTypeId=objectType.equals("0X01")?"1":objectType.equals("0X02")?"2":objectType.equals("0X03")?"3":"";
            HashMap hashMap=new HashMap();
            hashMap.put("objectType",objectTypeId);
            //随即查询出一条问题
            pwCheckTheDutyIssue pwCheckTheDutyIssue=postMessageService.selectOne(topicType);
            //创建查询类
            pwCheckTheDutyMessage pwCheckTheDutyMessage=new pwCheckTheDutyMessage();
            pwCheckTheDutyMessage.setPlatformIds(platformIds);
            pwCheckTheDutyMessage.setChdId(pwCheckTheDutyIssue.getId());
            pwCheckTheDutyMessage.setRoleType(roleType);
            pwCheckTheDutyMessage.setPlatformId(platformId);
            pwCheckTheDutyMessage.setCheckTime(date1);
            pwCheckTheDutyMessage.setObjectType(objectType);
            pwCheckTheDutyMessage.setContentType(0);
            pwCheckTheDutyMessage.setEnterpriseId(enterpriseId);
            pwCheckTheDutyMessage.setRegionCode(regionCode);
            pwCheckTheDutyMessage.setuId(uId);
            //将查询数据添加到数据库
            int id =postMessageService.insertCheck(pwCheckTheDutyMessage);
            //添加问题,答案,选项等
            hashMap.put("question",pwCheckTheDutyIssue.getTopic());
            hashMap.put("pid",String.valueOf(platformIds));
            hashMap.put("msgId",String.valueOf(pwCheckTheDutyMessage.getMsgId()));
            if (objectType.equals("0X01")){
                String region=regionCode.substring(0,4);
                String messageObjectTypeId =region+RandomNumber.randomString(4,false);
                hashMap.put("objectId",platformIds);
                int i=postMessageService.updateObjectType(pwCheckTheDutyMessage.getMsgId(),String.valueOf(platformIds));
            }
            if (objectType.equals("0X02")){
                //获取业户的经营许可证号
                String businessCertificate=disEnterpriseMapper.selectBusiness(enterpriseId);
                hashMap.put("objectId",businessCertificate);
                int i=postMessageService.updateObjectType(pwCheckTheDutyMessage.getMsgId(),businessCertificate);
            }
            if (objectType.equals("0X03")){
                //获取业户的经营许可证号
                String businessCertificate="0X000000000000000000000000";
                hashMap.put("objectId",businessCertificate);
                int i=postMessageService.updateObjectType(pwCheckTheDutyMessage.getMsgId(),businessCertificate);
            }
            Map<String,String>headMap=new HashMap<>();
            headMap.put("clientCode",clientCode);
            Map map=new HashMap();
            JSONObject jsonString = new JSONObject();
            String body= jsonString.toJSONString(hashMap);
            String path="/dis/v1/platform/check";
            String result= HttpClientUtils.doPostTestThree(path,headMap,map, body);
            log.info(result);
            int count=1;
            response.setCode(RetCode.SUCCESS);
            response.setMsg("执行成功");
            response.setData(count);

        }catch (Exception e){
            e.printStackTrace();
        }
        return response;

    }


    //=======查岗随即问题展示一条===============
    @ApiOperation(value = "查岗随即问题展示一条")
    @RequestMapping(value = "/queryOne",method = RequestMethod.GET)
    public Response getOne(String topicType){
        Response response=new Response();
        //随即查询出一条问题
        pwCheckTheDutyIssue pwCheckTheDutyIssue=postMessageService.selectOne(topicType);
        if (pwCheckTheDutyIssue==null){
            response.setData(null);
            response.setCode(RetCode.SUCCESS);
            response.setMsg("执行成功");
            return response;
        }
        Map map=new HashMap();
        map.put("id",pwCheckTheDutyIssue.getId());
        response.setData(map);
        response.setCode(RetCode.SUCCESS);
        response.setMsg("执行成功");
        return response;
    }



    //=======接入平台(查岗记录(查询下级))---我的下级查岗管理(platformIds)---====================
    @ApiOperation(value = "接入平台(查岗记录(查询下级))")
    @RequestMapping(value = "/IsAnswerIssue",method = RequestMethod.GET)
    public LayuiTablePagingResult IsAnswerIssue(String roleType,Integer page,Integer size,Integer contentType,String startTime,String endTime,Integer uId,Integer platformIds,String objectType){
       LayuiTablePagingResult result=null;
       try {
            PageHelper.startPage(page,size);
            List<Map<String,Object>> pwCheckTheDutyMessageList=pwCheckTheDutyMessageMapper.selectIsAnswerIssue(roleType,contentType,startTime,endTime,uId,platformIds,objectType);
            PageInfo pageInfo=new PageInfo(pwCheckTheDutyMessageList);
            result = new LayuiTablePagingResult();
            result.setCode(RetCode.SUCCESS.getCode());
            result.setMsg(RetCode.SUCCESS.getMsg());
            result.setCount(pageInfo.getTotal());
            result.setData(pageInfo.getList());
           Long totalPages = pageInfo.getTotal() / size;
           if (pageInfo.getTotal() % size != 0){
               totalPages ++;
           }
           result.setTotalPages(totalPages);
       }catch (Exception e){
           e.printStackTrace();
       }
       return result;
    }

    //=======我的查岗管理=============
    @ApiOperation(value = "我的查岗管理----建议废除")
    @RequestMapping(value = "/showPlatformMessage",method = RequestMethod.GET)
    public LayuiTablePagingResult showPlatformMessage(Integer page,Integer size,Integer isReply,Date startTime,Date endTime,Integer platformId){
        LayuiTablePagingResult result=null;
        try {
            PageHelper.startPage(page,size);
                List<Map<String,Object>>platformDetail=pwCheckTheDutyMessageMapper.selectPlatformDetail(platformId,startTime,endTime,isReply);
                PageInfo pageInfo=new PageInfo(platformDetail);
                result = new LayuiTablePagingResult();
                result.setCode(RetCode.SUCCESS.getCode());
                result.setMsg(RetCode.SUCCESS.getMsg());
                result.setCount(pageInfo.getTotal());
                result.setData(pageInfo.getList());
            Long totalPages = pageInfo.getTotal() / size;
            if (pageInfo.getTotal() % size != 0){
                totalPages ++;
            }
            result.setTotalPages(totalPages);
        }catch (Exception e){
         e.printStackTrace();
        }
        return result;

    }

    //========查岗详情记录===========
    @ApiOperation(value = "查岗详情记录")
    @RequestMapping(value = "/detailsMessage",method = RequestMethod.GET)
    public Response getDetailsMessage(Integer megId){
        Response response=new Response();
        List<Map<String,Object>> pwCheckTheDutyMessage=pwCheckTheDutyMessageMapper.selectMsgId(megId);
        response.setData(pwCheckTheDutyMessage);
        response.setCode(RetCode.SUCCESS);
        response.setMsg("执行成功");
        return response;
    }


    @ApiOperation(value = "下发报文消息类型")
    @RequestMapping(value = "/showMessageType",method = RequestMethod.GET)
    public Response getMessageType(){
        Response response=new Response();
        List<Map<String,Object>>messageTypeList=disDictionaryMapper.selectMessageType();
        response.setData(messageTypeList);
        response.setCode(RetCode.SUCCESS);
        response.setMsg("执行成功");
        return response;
    }



    //=======查岗记录回调接口====================
    @ApiOperation(value = "查岗记录回调接口")
    @RequestMapping(value = "/platform/platformGuardCallback",method = RequestMethod.POST)
    @JwtIgnore
    public Response getCallback(Date updateTime,Integer msgId,String content,String clientCode){
        Response response=new Response();
        try {
                int i=postMessageService.updateContent(updateTime,msgId,content);
                response.setData(i);
                response.setCode(RetCode.CALLBACK_SUCCESS);
                log.info("查岗回调信息-->"+"应答时间:"+updateTime+"  消息id:"+msgId+"  应答内容:"+content);
        }catch (Exception e){
            e.printStackTrace();
        }
        return response;
    }




    //=======下发报文根据条件搜索平台或企业====================
    @ApiOperation(value = "下发报文或查岗根据条件搜索平台或企业")
    @RequestMapping(value = "/searchObject",method = RequestMethod.GET)
    public Response getObject(Integer platformId,String platformCode,String objectType){
        Response response=new Response();
        try {
                if (objectType.equals("0X00")){
                    //下级平台所属单一平台
                    List<Map<String,Object>>platformList=disPlatformMapper.selectPlatform(platformCode);
                    response.setData(platformList);
                    response.setCode(RetCode.SUCCESS);
                    response.setMsg("执行成功");
                    return response;
                }else if (objectType.equals("0X02")){
                    //下级平台所属单一业户
                    List<Map<String,Object>>enterpriseList=disEnterpriseMapper.searchEnterprise(platformId);
                    response.setData(enterpriseList);
                    response.setCode(RetCode.SUCCESS);
                    response.setMsg("执行成功");
                    return response;
                }
        }catch (Exception e){
            e.printStackTrace();
        }
        return response;
    }



    //=======下发报文接口====================
    @ApiOperation(value = "下发报文接口")
    @MyLog(value = "下发报文")
    @RequestMapping(value = "/issueMessage",method = RequestMethod.POST)
        public Response issueMessage(pwMessageList pwMessageList,String organizationId,HttpServletRequest request){
        Response response=new Response();
        try {
            Boolean flag=listerUtil.getRoleType(request);
            if (flag==false){
                response.setCode(RetCode.ACCOUNT_EXIST);
                response.setMsg("此账号为监管员账号,不可进行操作");
                return response;
            }
            Map map = new HashMap();
            pwMessage pwMessage1 = new pwMessage();
            pwMessage1.setIsReply(-1);
            pwMessage1.setPlatformIds(pwMessageList.getPlatformIds());//接入平台id
            pwMessage1.setPlatformId(pwMessageList.getPlatformId());//下发平台id
            pwMessage1.setuId(pwMessageList.getuId());//登陆平台的用户id
            pwMessage1.setMessageContent(pwMessageList.getMessageContent());//下发报文内容
            pwMessage1.setEnterpriseId(pwMessageList.getEnterpriseId());//业户id
            //pwMessage1.setRoleType(pwMessageList.getRoleType());
            pwMessage1.setMessageObjectType(pwMessageList.getMessageObjectType());//下发报文对象
            int i = postMessageService.insertMessage(pwMessage1);//返回的主键id
            if (pwMessage1.getMessageObjectType().equals("0X00")||pwMessage1.getMessageObjectType().equals("0X01")){//如果下发报文的对象 OBJECT_ID 是 < OXO2
                String platform=postMessageService.selectPlatformId(pwMessage1.getId());
                String AreaCode=disPlatformMapper.selectAccessCode(Integer.parseInt(platform));//地区码
                String regionCode=AreaCode.substring(0,4);
                String messageObjectTypeId =regionCode+RandomNumber.randomString(4,false);
                int ss=postMessageService.updateMessage(pwMessage1.getId(),messageObjectTypeId);
                map.put("msgId",String.valueOf(pwMessage1.getId()));//消息id
                map.put("content",pwMessageList.getMessageContent());//报文内容
                map.put("objectId",messageObjectTypeId);//下发报文对象id
                map.put("pid",String.valueOf(pwMessageList.getPlatformIds()));//接入平台id
                map.put("pids",String.valueOf(pwMessageList.getPlatformId()));//下发平台id
                map.put("objectType",pwMessageList.getMessageObjectType());//下发报文对象类型
                map.put("organizationId",organizationId);//必选 登录用户所属的机构id
                Map<String,String>headMap=new HashMap<>();
                headMap.put("clientCode",clientCode);
                String url="http://"+Ip+":"+port+"/dis/v1/platform/message";
                String result=HttpClientUtils.doPost(url,headMap, map);
                log.info(result);
            }else if (pwMessage1.getMessageObjectType().equals("OXO2")){//如果下发报文的对象 OBJECT_ID 是 = OXO2
                        String messageObjectTypeId=enterpriseService.selectBusinessCertificate(pwMessageList.getEnterpriseId());//根据车辆id查询出业户经营许可证
                        int ss=postMessageService.updateMessage(pwMessage1.getId(),messageObjectTypeId);
                        map.put("msgId",String.valueOf(pwMessage1.getId()));// 必选 消息id
                        map.put("content",pwMessage1.getMessageContent());// 必选 查岗内容
                        map.put("objectId",messageObjectTypeId);//必选 查岗对象id
                        map.put("objectType",pwMessage1.getMessageObjectType());// 必选 查岗对象类型
                        map.put("pid",String.valueOf(pwMessageList.getPlatformIds()));//接入平台id
                        map.put("eids",pwMessage1.getEnterpriseId());//下发企业id
                        map.put("organizationId",organizationId);//必选 登录用户所属的机构id
                        String url="http://"+Ip+":"+port+"/dis/v1/platform/message";
                        Map<String,String>headMap=new HashMap<>();
                        headMap.put("clientCode",clientCode);
                        String result=HttpClientUtils.doPost(url,headMap, map);
                        System.out.println(result);
                }else {
                        String messageObjectTypeId="0X000000000000000000000000";
                        int ss=postMessageService.updateMessage(pwMessage1.getId(),messageObjectTypeId);
                        map.put("msgId",String.valueOf(pwMessage1.getId()));// 必选 消息id
                        map.put("content",pwMessage1.getMessageContent());// 必选 查岗内容
                        map.put("objectId",messageObjectTypeId);// 必选 查岗对象id
                        map.put("pid",String.valueOf(pwMessageList.getPlatformIds()));//接入平台id
                        map.put("objectType",pwMessage1.getMessageObjectType());// 必选 查岗对象类型
                        map.put("organizationId",organizationId);//必选 登录用户所属的机构id
                        String url="http://"+Ip+":"+port+"/dis/v1/platform/message";
                        Map<String,String>headMap=new HashMap<>();
                        headMap.put("clientCode",clientCode);
                        String result=HttpClientUtils.doPost(url,headMap, map);
                        log.info(result);
                    }
                response.setData(1);
                response.setCode(RetCode.SUCCESS);
                response.setMsg("执行成功");
                return response;
        }catch (Exception e){
            e.printStackTrace();
        }
        return response;
    }

    //=======下发报文回调接口====================
    @ApiOperation(value = "下发报文回调接口")
    @RequestMapping(value = "/report/result",method = RequestMethod.POST)
    @JwtIgnore
    public Response getResult(Date responseTime,String clientCode,Integer msgId,String content){
        Response response=new Response();
        try {
             Integer sum=postMessageService.selectResponseSum(msgId);
             Integer count=sum+1;
             int i=postMessageService.updateResult(responseTime,msgId,content,count);
             response.setData(i);
             response.setCode(RetCode.SUCCESS);
             response.setMsg("执行成功");
        }catch (Exception e){
            e.printStackTrace();
        }
        return  response;
    }



    //=======下发车辆报文接口==============
    @ApiOperation(value = "下发车辆报文接口")
    @RequestMapping(value = "/sendPacket",method = RequestMethod.POST)
    public Response getSendPacket(Integer platformId,String vehicleIds,String msgPriority,String msgContent,HttpServletRequest request){
        Response response=new Response();
        try {
            Boolean flag=listerUtil.getRoleType(request);
            if (flag==false){
                response.setCode(RetCode.ACCOUNT_EXIST);
                response.setMsg("此账号为监管员账号,不可进行操作");
                return response;
            }
            pwVehicleMessage pwVehicleMessage=new pwVehicleMessage();
            String[] vehicleList=vehicleIds.split(",");
            for (String vehicleId : vehicleList) {
                pwVehicleMessage.setIsResponse("-1");
                pwVehicleMessage.setMsgPriority(msgPriority);
                pwVehicleMessage.setMsgContent(msgContent);
                pwVehicleMessage.setPlatformId(platformId);
                pwVehicleMessage.setVehicleId(Integer.valueOf(vehicleId));
                Date date=new Date();
                pwVehicleMessage.setCreateTime(date);
                int id=pwVehicleMessageMapper.insertSelective(pwVehicleMessage);
            }
            Map map=new HashMap();
            map.put("platformId",String.valueOf(platformId));//必传 平台id
            map.put("msgId",String.valueOf(pwVehicleMessage.getId()));//必传 消息头id
            map.put("msgPriority",msgPriority);//必传 消息的优先级,定义如下0x00:紧急;0x01:一般;
            map.put("msgContent",msgContent);//必传 下发报文内容
            Map<String,String>headMap=new HashMap<>();
            headMap.put("clientCode",clientCode);
            String path="/dis/v1/platform/sendPacket";
            String result=HttpClientUtils.doPostTestThree(path,headMap,map,vehicleIds);
            System.out.println(result);
            response.setData(1);
            response.setCode(RetCode.SUCCESS);
            response.setMsg("执行成功");
            return response;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;

    }

    //======下发报文回调接口=============
    @ApiOperation(value = "下发车辆报文回调接口")
    @RequestMapping(value = "/sendPacket/result",method = RequestMethod.POST)
    @JwtIgnore
    public void result(Integer msgId,Date answerTime,String result){
        pwVehicleMessage pwVehicleMessage=new pwVehicleMessage();
        pwVehicleMessage.setAnswerTime(answerTime);
        pwVehicleMessage.setIsResponse("1");
        pwVehicleMessage.setMsgResponse(result);
        pwVehicleMessage.setId(msgId);
        pwVehicleMessageMapper.updateByPrimaryKeySelective(pwVehicleMessage);
    }


    @ApiOperation(value = "车辆交互记录")
    @RequestMapping(value = "/vehicleInteraction",method = RequestMethod.GET)
    public LayuiTablePagingResult getVehicleInteraction(Integer page,Integer size,Integer platformId){
        LayuiTablePagingResult result=null;
        PageHelper.startPage(page,size);
        List<Map<String,Object>>vehicleMessageList=pwVehicleMessageMapper.selectByPlatformId(platformId);
        PageInfo pageInfo=new PageInfo(vehicleMessageList);
        result = new LayuiTablePagingResult();
        result.setCode(RetCode.SUCCESS.getCode());
        result.setMsg(RetCode.SUCCESS.getMsg());
        result.setCount(pageInfo.getTotal());
        result.setData(pageInfo.getList());
        Long totalPages = pageInfo.getTotal() / size;
        if (pageInfo.getTotal() % size != 0){
            totalPages ++;
        }
        result.setTotalPages(totalPages);

        return result;
    }


    //======查岗对象展示(平台或企业)==========
/*    @ApiOperation(value = "查岗对象展示(平台或企业)")
    @RequestMapping(value = "/showObjectType",method = RequestMethod.GET)
    public Response getQueryAll(String objectType,Integer platformId,String regionCode){
       Response response=new Response();
       if (objectType.equals("0X01")){//当前连接的下级平台
         List<Map<String,Object>>platform=disPlatformMapper.selectPlatform(regionCode);
           response.setData(platform);
           response.setCode(RetCode.SUCCESS);
           response.setMsg("执行成功");
       }
       if (objectType.equals("0X02")||objectType.equals("0X03")){//下级平台所属所有业户
           List<Map<String,Object>>enterpriseList=disPlatformMapper.selectByAreaCode(regionCode,platformId);
           response.setData(enterpriseList);
           response.setCode(RetCode.SUCCESS);
           response.setMsg("执行成功");
       }
       return response;
    }*/

    //========查岗记录信息=========
    @ApiOperation(value = "查岗记录信息")
    @RequestMapping(value = "/postrecord/info",method = RequestMethod.GET)
    public JSONObject info(String postTarget,String responseResult,String startTime,String endTime,String limit,String page){
      Map map=new HashMap();
      map.put("postTarget",postTarget);//查岗对象
      map.put("responseResult",responseResult);//应答结果
      map.put("startTime",startTime);//查岗开始时间
      map.put("endTime",endTime);//查岗结束时间
      map.put("limit",limit);//页面记录数
      map.put("page",page);//页码
        Set<String> set = map.keySet();
        Iterator<String> it = set.iterator();
        while (it.hasNext()) {
            String str = it.next();
            if(map.get(str)==null || map.get(str) =="null"|| map.get(str)==""){
                map.remove(str);
                set = map.keySet();
                it = set.iterator();
            }
        }
        Map<String,String>headMap=new HashMap<>();
        headMap.put("clientCode",clientCode);
        String url="http://"+Ip+":"+port+"/dis/statistics/postrecord/info";
        String result=HttpClientUtils.doGet(url,headMap,map);
        JSONObject json= JSONObject.parseObject(result);
        return json;
    }

    @ApiOperation(value = "报文信息批量删除")
    @RequestMapping(value = "/messageDeleteBatch",method = RequestMethod.POST)
    public Response deleteBatch(Integer[] ids){
        Response response=new Response();
        try {
            for (Integer id : ids) {
                int count=pwMessageMapper.deleteBatch(id);
                response.setCode(RetCode.SUCCESS);
                response.setMsg("操作成功");
                response.setData(count);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return response;
    }

}





































































